package com.hua.api.core.servlet;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.hua.api.core.util.StringUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet(name = "share",urlPatterns = "/api/share/qrcode")
public class ShareQrcode extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static  String url = "";
    private static String real_path="";
    @Override
    public void destroy() {
        super.destroy();
    }
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        try{
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setCharacterEncoding("utf-8");
            request.setCharacterEncoding("UTF-8");
            String url = request.getParameter("url");
            if(null != url){
                url = StringUtil.decode(url,"utf-8");
            }else{
                url = "http://www.hua1000.com";
            }
            Integer w = NumberUtil.parseInt(request.getParameter("w"),392);

            Integer h = NumberUtil.parseInt(request.getParameter("h"),392);
            String icon = request.getParameter("icon");
            // 邀请码
            // System.out.println(url+"     "+w+"    "+h);
            ImageIO.write(create_image(url,w,h,icon), "jpg", response.getOutputStream());

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            response.getOutputStream().close();
        }
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        real_path=config.getServletContext().getRealPath("/");
        super.init();
    }

    private static BufferedImage create_image(String sms_info, Integer width, Integer height, String icon){
        QrConfig config = QrConfig.create().
                setWidth(width)
                .setHeight(height)
                .setMargin(1)
                .setQrVersion(5);
        if("alipay".equals(icon)){
            config.setImg(real_path+"images/alipay.png");
        }
        return QrCodeUtil.generate(sms_info,config);
    }

}
